package com.duke.shaking.interaction;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;


import com.androidquery.AQuery;
import com.duke.shaking.pojo.ChatFriend;
import com.duke.shaking.pojo.Message;
import com.duke.shaking.pojo.User;
import com.duke.shaking.storage.DataManager;
import com.duke.shaking.BaseActivity;
import com.duke.shaking.R;

import android.content.Context;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.app.Activity;

public class MessagesListAdapter extends BaseAdapter {
	private final long timestampShowIntval = 2 * 60 * 1000;
	private List<Message> messages;
	private LayoutInflater inflater;
	private AQuery aQuery;
	private int screenWidth;
	public MessagesListAdapter(Context context, List<Message> messages) {
		this.messages = messages;
		inflater = LayoutInflater.from(context);
		aQuery = new AQuery(context);
		DisplayMetrics dm = new DisplayMetrics();  
		((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(dm);
		screenWidth = dm.widthPixels;
	}
	
	public int getCount() {
		if (messages != null) {
			return messages.size();
		}
		return 0;
	}

	public Object getItem(int position) {
		if (position > 0 && messages != null && position < messages.size()) {
			return messages.get(position);
		}
		return null;
	}

	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public int getItemViewType(int position) {
		if (position < 0 || messages == null || position >= messages.size()) {
			return Message.MSG_DIRECTION_FROM;
		}
		Message msg = messages.get(position);
		if (msg != null) {
			return msg.getDirection();
		}
		return Message.MSG_DIRECTION_FROM;
	}
	
	@Override
	public int getViewTypeCount() {
		return 2;
	}
	
	public View getView(int position, View convertView, ViewGroup parent) {
		ChatHolder chatHolder = null;
		if (position < 0 || messages == null || position >= messages.size()) {
			return null;
		}
		Message msg = messages.get(position);
		
		if (convertView == null) {
			chatHolder = new ChatHolder();
			if (msg.getDirection() == Message.MSG_DIRECTION_FROM) {
				convertView = inflater.inflate(R.layout.chat_from_item, null);
			}else {
				convertView = inflater.inflate(R.layout.chat_to_item, null);
			}
			chatHolder.txt_timestamp = (TextView) convertView.findViewById(R.id.txt_timestamp);
			chatHolder.img_avatar = (ImageView) convertView.findViewById(R.id.img_avatar);
			chatHolder.txt_content = (TextView) convertView.findViewById(R.id.txt_content);
			chatHolder.txt_content.setMaxWidth(screenWidth - 150);
			chatHolder.txt_msg_state = (TextView)convertView.findViewById(R.id.txt_msg_state);
			convertView.setTag(chatHolder);
			//LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)convertView.getLayoutParams();
			//lp.gravity = Gravity.BOTTOM;
			//convertView.setLayoutParams(lp);
			
		}else {
			chatHolder = (ChatHolder)convertView.getTag();
		}
		boolean timeShow = false;
		if (position == 0) {
			timeShow = true;
		}
		else if (position > 0){
			Message lastMsg = messages.get(position - 1);
			if (lastMsg != null
				&& lastMsg.getRecvTime() != null
			    && msg.getRecvTime() != null
				&& msg.getRecvTime().getTime() 
					> (lastMsg.getRecvTime().getTime() + timestampShowIntval)) {
				timeShow = true;
			}
		}
		if (timeShow && msg.getRecvTime() != null) {
			chatHolder.txt_timestamp.setVisibility(View.VISIBLE);
			Date recvTime = msg.getRecvTime();
			Date today = new Date();
			String fmt = "";
			if (recvTime.getYear() == today.getYear()
				&& recvTime.getMonth() == today.getMonth()
				&& recvTime.getDate() == today.getDate()) {
				fmt = "HH:mm";
			}
			else {
				fmt = "yyyy-MM-dd HH:mm";
			}
			SimpleDateFormat formatter = new SimpleDateFormat(fmt, Locale.CHINA);
			chatHolder.txt_timestamp.setText(formatter.format(recvTime));
		}
		else {
			chatHolder.txt_timestamp.setVisibility(View.GONE);
		}
		
		boolean blank = true;
		if (msg.getDirection() == Message.MSG_DIRECTION_FROM) {
			if (msg.getFromId() != null) {
				ChatFriend f = DataManager.getShared().getFriendById(msg.getFromId());
				if (f.getAvatarUrl() != null) {
					aQuery.id(chatHolder.img_avatar).image(f.getAvatarUrl(), 
						true, true, 0, R.drawable.blank_avatar,null, 0);
					blank = false;
				}
			}
		}
		else {
			User me = BaseActivity.getMe();
			if (me != null && me.getAvatarUrl() != null) {
				Log.i("shaking", "set my avater: " + me.getAvatarUrl());
				aQuery.id(chatHolder.img_avatar).image(me.getAvatarUrl(), 
						true, true, 0, R.drawable.blank_avatar,null, 0);
				blank = false;
			}
			if (chatHolder.txt_msg_state != null) {
				if (msg.getSendState() == Message.SEND_STATE_SUCCESS) {
					chatHolder.txt_msg_state.setText(R.string.tip_msg_sent);
					chatHolder.txt_msg_state.setBackgroundResource(R.drawable.barkgreen);
				}
				else if (msg.getSendState() == Message.SEND_STATE_FAILED) {
					chatHolder.txt_msg_state.setText(R.string.tip_msg_failed);
					chatHolder.txt_msg_state.setBackgroundResource(R.drawable.red);
				}
				else {
					chatHolder.txt_msg_state.setText(R.string.tip_msg_sending);
					chatHolder.txt_msg_state.setBackgroundResource(R.drawable.orange);
				}
			}
		}
		if (blank) {
			chatHolder.img_avatar.setImageResource(R.drawable.blank_avatar);
		}
		chatHolder.txt_content.setText(msg.getContent());
		
		return convertView;
	}

	private class ChatHolder{
		public TextView txt_timestamp;
		public ImageView img_avatar;
		public TextView txt_content;
		public TextView txt_msg_state;
	}
}
